const express = require('express');
const router = express.Router();

const FocusModel = require('../../model/focusModel');
const tools = require('../../model/tools');
const fs = require('fs');

router.get('/', async (req, res)=>{
  let list = await FocusModel.find({});
  res.render('admin/focus/index.html', {
    list
  })
});

router.get('/add', (req, res)=>{
  res.render('admin/focus/add.html');
});

router.post('/doAdd', tools.multer().single('focus_img'), async (req, res)=>{
  try {
    // static\uploads\20220517\focus_img-1652756599729.jpg
    // 从第7个字符开始，前边的去掉 --> uploads\20220517\focus_img-1652756599729.jpg
    let focus_img = req.file?req.file.path.substring(7):'';
    let result = new FocusModel(Object.assign(req.body, {focus_img: focus_img}))
    await result.save();
    res.render('admin/public/success.html', {
      message: '增加轮播图成功',
      redirectUrl: `/${req.app.locals.adminPath}/focus`
    });
  } catch (error) {
    res.render('admin/public/error.html', {
      message: '增加轮播图失败',
      redirectUrl: `/${req.app.locals.adminPath}/focus`
    });
  }
})

router.get('/edit', async (req, res)=>{
  let id = req.query.id;
  let list = await FocusModel.find({_id: id});
  res.render('admin/focus/edit.html', {
    list: list[0]
  });
});

router.post('/doEdit', tools.multer().single('focus_img'), async (req, res)=>{
  try {
    if(req.file){ //更新图片
      // 1.更改图片路径
      let focus_img = req.file?req.file.path.substring(7):'';
      let originImg = req.body.origin_img;
      await FocusModel.updateOne({_id: req.body.id}, Object.assign(req.body, {focus_img: focus_img}))
      // 2.删除原来的图片
      if(originImg){
        await fs.unlink('static/'+originImg, err=>{
          if(err){
            console.log(err);
          }
        })
      }
    }else{
      await FocusModel.updateOne({_id: req.body.id}, req.body)
    }
    res.render('admin/public/success.html', {
      message: '修改轮播图成功',
      redirectUrl: `/${req.app.locals.adminPath}/focus`
    });
  } catch (error) {
    res.render('admin/public/error.html', {
      message: '修改轮播图失败',
      redirectUrl: `/${req.app.locals.adminPath}/focus/edit?id=${req.body.id}`
    });
  }
});

router.get('/delete', async (req, res)=>{
  let id = req.query.id;
  let resultList = await FocusModel.find({_id: id});
  let delResult = await FocusModel.deleteOne({_id: req.query.id});
  //删除图片
  if(delResult.ok == 1 && delResult.n == 1){
    if(resultList[0].focus_img){
      await fs.unlink('static/'+resultList[0].focus_img, err=>{
        if(err){
          console.log(err);
        }
      })
    }
  }
  res.render('admin/public/success.html', {
    message: '删除轮播图成功',
    redirectUrl: `/${req.app.locals.adminPath}/focus`
  });
})

module.exports = router;